package net.mayee.alice.service.admin.account;

import net.mayee.alice.dao.admin.account.RoleDao;
import net.mayee.alice.entity.admin.account.Role;
import net.mayee.alice.entity.admin.account.UserRole;
import net.mayee.common.utils.Encodes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service("RoleService")
public class RoleService {

    @Autowired
    private RoleDao roleDao;

    public Role getRole(String uuid) {
        return roleDao.get(uuid);
    }

    public void insertRole(Role role) {
        roleDao.insert(role);
    }

    public void updateRole(Role role) {
        roleDao.update(role);
    }

    public void removeRole(String uuid) {
        roleDao.remove(uuid);
    }

    public int count(Map<String, Object> parameters) {
        return roleDao.count(parameters);
    }

    public List<Role> searchByLimit(Map<String, Object> parameters) {
        return roleDao.searchByLimit(parameters);
    }

    public Role getByRoleKey(String roleKey) {
        return roleDao.getByRoleKey(roleKey);
    }

    public List<Role> getAll() {
        return roleDao.getAll();
    }

    public List<Role> getRolesByUser(String uid){
        return roleDao.getRolesByUser(uid);
    }



    public boolean saveUserRole(String uid, String j) {
        Role role = roleDao.get(uid);
        if (role != null) {
            roleDao.removeUserRole(uid);

            com.alibaba.fastjson.JSONArray josnArray =
                    com.alibaba.fastjson.JSON.parseArray(Encodes.unescapeHtml(j));
            for (Object obj : josnArray) {
                if (obj instanceof com.alibaba.fastjson.JSONObject) {
                    com.alibaba.fastjson.JSONObject JSONObject = (com.alibaba.fastjson.JSONObject) obj;
                    String user_uid = JSONObject.getString("id");
                    UserRole ur = new UserRole();
                    ur.setUserUuid(user_uid);
                    ur.setRoleUuid(uid);
                    roleDao.insertUserRole(ur);
                }
            }
            return true;
        }
        return false;
    }

    public HashMap<String, String> getPermissionsByRole(String uid){
        HashMap<String, String> map = new HashMap<String, String>();
        Role role = roleDao.get(uid);
        if (role != null && role.getPermissions() != null) {
            String[] perStr = role.getPermissions().split(",");
            for(String per : perStr){
                String[] kv = per.split(":");
                if(StringUtils.isNotBlank(kv[0]) && StringUtils.isNotBlank(kv[1])){
                    map.put(kv[0],kv[1].toUpperCase());
                }
            }
        }
        return map;
    }



}
